<!-- 屏幕监控 -->
<template>
  <div>
    <el-form
      :inline="true"
      :model="editorForm"
      :rules="editorFormRules"
      ref="editorFormRef"
      label-width="100px"
      size="small"
      :show-message="false"
      :hide-required-asterisk="true"
      :status-icon="false"
    >
      <el-row>
        <el-col :span="10">
          <el-form-item :label="$t('宽度')+':'" prop="width">
            <el-input
              v-model="editorForm.width"
              autocomplete="off"
              maxlength="5"
              :show-word-limit="false"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item :label="$t('高度')+':'" prop="height">
            <el-input
              v-model="editorForm.height"
              autocomplete="off"
              maxlength="5"
              :show-word-limit="false"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <bs-screen-capture-button-icon
            :show-icon="false"
            @click.native="doCap"
            v-has="'TERMINAL_STATUS_SCREEN'"
          ></bs-screen-capture-button-icon>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :span="24">
        <!-- 添加的元素 -->
        <elements></elements>
        <div
          :class="[className]"
          :style="[computedStyle]"
          class="template-main-wrapper"
        >
          <div
            :style="[computedInnerStyle]"
            class="compont"
            id="compont"
            ref="capture"
          ></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { Loading } from 'element-ui'
import DeviceMonitorApi from '@/api/device'
import Elements from '../../../../media/components/TemplateComponents/Elements'
import { TemplateOptions } from '@/mixins/ScreenTemplate.js'
import { mapGetters } from 'vuex'

export default {
  name: 'ScreenStatus',
  data() {
    const width = 4000
    const height = 4000
    return {
      editorForm: {
        width: 1920,
        height: 1080
      },
      tableData: [],
      monitorPic: require('../../images/monitoring.gif'),
      loading: null,
      editorFormRules: {
        width: { required: true, message: '请输入屏幕宽度', trigger: 'blur' },
        height: { required: true, message: '请输入屏幕高度', trigger: 'blur' },
      },
      twidget: [],
      widgetData: {},
      wrapperWidth: 760,
      wrapperHeight: 425,
      templateOpts: {
        width: width,
        height: height,
      },
      timmer: null
    }
  },
  props: {
    id: {
      default: 0,
    },
    className: {
      type: String,
      default: '',
    },
    deviceWidgetData: {
      default: () => {}
    }
  },
  mixins: [TemplateOptions],
  components: {
    Elements
  },
  mounted() {
    this.$nextTick(function () {
      if(this.deviceWidgetData) {
        this.resetTwidget(this.deviceWidgetData.argus)
        this.templateOpts = {
          width: this.deviceWidgetData.width,
          height: this.deviceWidgetData.height
        }
      }
    })
  },
  created() {
    this.$eventBus.$on('doRefreshScreen', this.doRefreshScreen)
  },
  destroyed() {
    if (this.timmer) {
      clearInterval(this.timmer)
      this.timmer = null
    }
    this.$eventBus.$off('doRefreshScreen')
  },
  methods: {
    async doCap() {
      this.$refs.editorFormRef.validate(async (valid) => {
        if (valid) {
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          this.editorForm.terminalId = this.id
          const res = await DeviceMonitorApi.commandPrintScreen(this.editorForm)
          
          if (this.loading) {
            this.loading.close()
            this.loading = null
          }
          this.$alert(
            '提示',
            'sendPromptOfScreenCapture'
          )
          if (this.timmer) {
            clearInterval(this.timmer)
          }
          this.doCapResult()
        } else {
          let index = 0
          this.$refs.editorFormRef.fields.forEach(field => {
            if(field.validateMessage) {
              if(index === 0) {
                console.log(field.validateMessage)
                this.$message.error(field.validateMessage)
                this.validateMsg=[]
              }
              index ++
            }
          })
          return
        }
      })
    },
    // 发送截屏后获取结果
    doCapResult() {
      this.timmer = setInterval(() => {
        this.resetTwidget(this.deviceWidgetData.argus)
      }, 2000);
    },
    // 刷新屏幕截屏
    doRefreshScreen() {
      this.resetTwidget(this.deviceWidgetData.argus)
    },
    async resetTwidget(val) {
        if(!val) return
        let data = null
        if(this.screenData) {
          try {
            data = eval('(' + this.screenData + ')')
          }catch(error) {}
        }
        let imgJson = []
        if(data) {
          imgJson = data.list
        }
        if(imgJson.length > 0) {
          val.forEach(item => {
              imgJson.forEach(img => {
                  if(Number(item.id) === Number(img.id)) {
                    item.screen = img.path
                  }
              })
          })
        } else {
          if(val) {
            val.forEach(item => {
              item.screen = '1'
            })
          }
        }
        this.twidget = val
        this.layoutInit()
    }
  },
  watch:{
    deviceWidgetData(val) {
        if(val) {
            this.resetTwidget(val.argus)
            this.templateOpts = {
                width: val.width,
                height: val.height
            }
        }
    }
  },
  computed: {
    computedStyle() {
      let w = this.wrapperWidth
      let h = this.wrapperHeight
      if (typeof w === 'number') {
        w = isNaN(w) ? '' : `${w}px`
      }
      if (typeof h === 'number') {
        h = isNaN(h) ? '' : `${h}px`
      }
      let styles = {}
      if (w) styles.width = w
      if (h) styles.height = h

      return styles
    },
    computedInnerStyle() {
      const { width, height } = this.templateOpts // 现实模版宽高
      let { width: wrapWidth, height: wrapHeight } = this.computedStyle // 容器宽高
      wrapWidth = Number(wrapWidth.replace('px', ''))
      wrapHeight = Number(wrapHeight.replace('px', ''))

      let styleWidth // 最终模版在容器的宽
      let styleHeight // 最终模版在容器的高
      let wratio // 缩放比
      let hratio

      wratio = wrapWidth / width
      hratio = wrapHeight / height
      styleWidth = `${width * wratio}px`
      styleHeight = `${height * hratio}px`

      this.$nextTick(() => {
        this.iwidthPercent = wratio
        this.iheightPercent = hratio
        // 舞台已初始化好
        // 开始塞入组件
        this.layoutInit()
      })

      return {
        width: styleWidth,
        height: styleHeight,
      }
    },
    ...mapGetters(['screenData'])
  }
}
</script>

<style lang="scss" scoped>
.addWiget {
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-bottom: 1px solid $bg-e9;
  height: 48px;
}
.addWiget:hover {
  background-color: $defaultBlue;
  color:#fff;
}
.notclick {
  display: flex;
  justify-content: space-around;
  align-items: center;
  // text-decoration: line-through;
  border-bottom: 1px solid $bg-e9;
  height: 48px;
  pointer-events: none;
  filter: grayscale(10%);
  color: #ddd;
}

.template-main-wrapper {
  border: 1px solid $bg-e9;
  position: relative;

  .compont {
    background: $bg-f4;
  }
}
</style>